from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                            QTextEdit, QGroupBox, QFrame)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPalette

from models.data_models import DetectionResult, ImageInfo

class InfoPanel(QWidget):
    """信息面板类"""
    
    def __init__(self):
        super().__init__()
        self._init_ui()
        self._setup_styles()

    def _init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(5, 5, 5, 5)

        # 检测结果统计区域
        stats_group = QGroupBox("检测统计")
        stats_layout = QVBoxLayout(stats_group)

        # 天牛数量显示 - 使用更大的字体
        count_layout = QHBoxLayout()
        count_label = QLabel("天牛数量:")
        count_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))  # 更大的字体
        count_layout.addWidget(count_label)

        self.count_value_label = QLabel("0")
        self.count_value_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))  # 数值更大
        self.count_value_label.setStyleSheet("color: #e91e63; background-color: #fce4ec; padding: 5px 10px; border-radius: 4px;")
        count_layout.addWidget(self.count_value_label)
        count_layout.addStretch()
        stats_layout.addLayout(count_layout)

        # 置信度信息
        conf_layout = QHBoxLayout()
        conf_label = QLabel("平均置信度:")
        conf_label.setFont(QFont("Microsoft YaHei", 12))
        conf_layout.addWidget(conf_label)

        self.confidence_label = QLabel("--")
        self.confidence_label.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        self.confidence_label.setStyleSheet("color: #2196f3; background-color: #e3f2fd; padding: 3px 8px; border-radius: 3px;")
        conf_layout.addWidget(self.confidence_label)
        conf_layout.addStretch()
        stats_layout.addLayout(conf_layout)

        # 处理时间
        time_layout = QHBoxLayout()
        time_label = QLabel("处理时间:")
        time_label.setFont(QFont("Microsoft YaHei", 12))
        time_layout.addWidget(time_label)

        self.time_label = QLabel("--")
        self.time_label.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        self.time_label.setStyleSheet("color: #4caf50; background-color: #e8f5e9; padding: 3px 8px; border-radius: 3px;")
        time_layout.addWidget(self.time_label)
        time_layout.addStretch()
        stats_layout.addLayout(time_layout)

        layout.addWidget(stats_group)

        # 详细信息区域
        details_group = QGroupBox("详细信息")
        details_layout = QVBoxLayout(details_group)

        # 信息文本框 - 设置为可伸缩
        self.details_text = QTextEdit()
        self.details_text.setReadOnly(True)
        self.details_text.setFont(QFont("Consolas", 10))
        # 设置大小策略让文本框跟随父组件变化
        from PyQt5.QtWidgets import QSizePolicy
        self.details_text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.details_text.setMinimumHeight(200)
        details_layout.addWidget(self.details_text)

        layout.addWidget(details_group)

        # 让详细信息组占据剩余空间
        layout.setStretchFactor(stats_group, 0)
        layout.setStretchFactor(details_group, 1)
    
    def _setup_styles(self):
        """设置样式"""
        self.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #cccccc;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 10px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 8px 0 8px;
                color: #333333;
                font-size: 13px;
            }
            QLabel {
                color: #333333;
            }
            QTextEdit {
                border: 2px solid #e0e0e0;
                border-radius: 6px;
                background-color: #fafafa;
                selection-background-color: #e3f2fd;
                selection-color: #1976d2;
                padding: 8px;
                line-height: 1.4;
            }
            QTextEdit:focus {
                border-color: #2196F3;
                background-color: white;
            }
        """)
    
    def update_detection_info(self, result: DetectionResult):
        """更新检测信息"""
        if result is None:
            self.clear_info()
            return
        
        # 更新统计信息
        self.count_value_label.setText(str(result.count))
        
        if result.boxes:
            avg_confidence = sum(box.confidence for box in result.boxes) / len(result.boxes)
            self.confidence_label.setText(f"{avg_confidence:.2f}")
        else:
            self.confidence_label.setText("--")
        
        self.time_label.setText(f"{result.processing_time:.2f}s")
        
        # 更新详细信息
        details = self._format_detection_details(result)
        self.details_text.setHtml(details)
    
    def update_image_info(self, image_info: ImageInfo):
        """更新图像信息"""
        self.count_value_label.setText("0")
        self.confidence_label.setText("--")
        self.time_label.setText("--")
        
        details = self._format_image_details(image_info)
        self.details_text.setHtml(details)
    
    def clear_info(self):
        """清空信息"""
        self.count_value_label.setText("0")
        self.confidence_label.setText("--")
        self.time_label.setText("--")
        self.details_text.clear()
    
    def _format_detection_details(self, result: DetectionResult) -> str:
        """格式化检测详细信息"""
        html = f"""
        <div style="font-family: 'Microsoft YaHei', sans-serif; font-size: 12px; line-height: 1.5;">
            <h3 style="color: #2196f3; margin-bottom: 10px;">🔍 检测结果详情</h3>
            
            <div style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                <strong>图像路径:</strong><br>
                <span style="color: #666; font-size: 11px;">{result.image_path or '未知'}</span>
            </div>
            
            <div style="background-color: #e8f5e9; padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                <strong>检测参数:</strong><br>
                • 置信度阈值: <span style="color: #4caf50; font-weight: bold;">{result.confidence_threshold:.2f}</span><br>
                • 检测数量: <span style="color: #e91e63; font-weight: bold;">{result.count}</span><br>
                • 处理时间: <span style="color: #ff9800; font-weight: bold;">{result.processing_time:.3f}s</span>
            </div>
        """
        
        if result.boxes:
            html += """
            <div style="background-color: #fff3e0; padding: 10px; border-radius: 5px;">
                <strong>检测框详情:</strong><br>
                <table style="width: 100%; margin-top: 5px; font-size: 11px;">
                    <tr style="background-color: #e0e0e0; font-weight: bold;">
                        <td style="padding: 3px;">序号</td>
                        <td style="padding: 3px;">置信度</td>
                        <td style="padding: 3px;">位置</td>
                    </tr>
            """
            
            for i, box in enumerate(result.boxes[:10]):  # 只显示前10个
                html += f"""
                    <tr style="{'background-color: #f9f9f9;' if i % 2 == 0 else ''}">
                        <td style="padding: 3px;">{i+1}</td>
                        <td style="padding: 3px; color: #4caf50; font-weight: bold;">{box.confidence:.3f}</td>
                        <td style="padding: 3px; font-family: monospace;">({int(box.x1)},{int(box.y1)})-({int(box.x2)},{int(box.y2)})</td>
                    </tr>
                """
            
            if len(result.boxes) > 10:
                html += f"""
                    <tr>
                        <td colspan="3" style="padding: 5px; text-align: center; color: #666; font-style: italic;">
                            ... 还有 {len(result.boxes) - 10} 个检测框
                        </td>
                    </tr>
                """
            
            html += "</table></div>"
        else:
            html += """
            <div style="background-color: #ffebee; padding: 10px; border-radius: 5px; color: #d32f2f;">
                <strong>⚠️ 未检测到任何目标</strong>
            </div>
            """
        
        html += "</div>"
        return html
    
    def _format_image_details(self, image_info: ImageInfo) -> str:
        """格式化图像详细信息"""
        # 获取完整路径 - 使用 image_path 属性
        full_path = getattr(image_info, 'image_path', image_info.filename)
        
        html = f"""
        <div style="font-family: 'Microsoft YaHei', sans-serif; font-size: 12px; line-height: 1.5;">
            <h3 style="color: #ff9800; margin-bottom: 10px;">📁 图像信息</h3>
            
            <div style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                <strong>文件名:</strong><br>
                <span style="color: #333; font-weight: bold;">{image_info.filename}</span>
            </div>
            
            <div style="background-color: #e3f2fd; padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                <strong>文件路径:</strong><br>
                <span style="color: #666; font-size: 11px; word-break: break-all;">{full_path}</span>
            </div>
            
            <div style="background-color: #fff3e0; padding: 10px; border-radius: 5px;">
                <strong>状态:</strong><br>
                <span style="color: {'#4caf50' if image_info.is_processed else '#ff9800'}; font-weight: bold;">
                    {'✓ 已处理' if image_info.is_processed else '○ 未处理'}
                </span>
            </div>
        </div>
        """
        return html
